package cn.fl.capital.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import cn.cmm.base.framework.exception.BaseException;
import cn.fl.insurance.vo.InsCapFundVO;
import cn.fl.ref.fncprjbscinfo.util.DateUtil;
import cn.fl.upload.constant.UploadConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cmm.comm.facade.upload.constant.SysUlFilesRecConstant;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.capital.vo.CapFundVO;
import cn.lb.framework.poi.excel.ExcelImportUtil;
import cn.lb.framework.poi.excel.entity.ImportParams;

/**
 * Function: 资金导入
 * Created by Administrator on 2016/8/31.
 */
public class ImportFundList {

	private static final Logger logger = LoggerFactory.getLogger(ImportFundList.class);

    /**
     * 导入资金
     * @param filePath 源文件路径
     * @return
     */
    public static List<CapFundVO> importXls(String filePath){
        logger.info("导入资金="+filePath);
        ImportParams params = new ImportParams();
        params.setTitleRows(0);//标题占用行数
        params.setHeadRows(1);//表头占用行数
        params.setNeedSave(false);//是否保存文件

        List<CapFundVO> list = null;
        if(!filePath.contains("http")){
            File file=new File(PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_ROOT_PATH)+filePath);
            if(file.exists()){
                list = ExcelImportUtil.importExcel(file, CapFundVO.class, params);
            }
        }else{
            InputStream in= null;
            URLConnection connection=null;
            try {
                URL url=new URL(filePath);
                connection=url.openConnection();//打开连接 获得URLConnection类的对象
                connection.setConnectTimeout(10000);
                connection.setReadTimeout(60000);
                in=connection.getInputStream();
                list = ExcelImportUtil.importExcel(in, CapFundVO.class, params);
            } catch (IOException e) {
                BaseLogUtils.error(logger,"importXls","导入资金读取上传文件出错，"+e.getMessage());
			BaseLogUtils.error(logger, "-", "异常", e);
            } catch (Exception e) {
                BaseLogUtils.error(logger,"importXls","导入资金读取上传文件出错,"+e.getMessage());
			BaseLogUtils.error(logger, "-", "异常", e);
            } finally {
                if(null!=in){
                    try {
                        in.close();
                    } catch (IOException e) {
			BaseLogUtils.error(logger, "-", "异常", e);
                    }
                }
            }
        }

        if(CollectionUtils.isNotEmpty(list)){
            BaseLogUtils.info(logger,"importXls","导入资金="+filePath+",记录条数="+list.size());
            StringBuffer errMsg=null;
            for(CapFundVO vo:list){
                vo.setFundStatusCd("0");//正常
                errMsg=new StringBuffer("");
                if(StringUtils.isBlank(vo.getAcceptCode())){
                    errMsg.append("收款账号为空;");
                    vo.setFundStatusCd("1");//异常
                }
                if(StringUtils.isBlank(vo.getAcceptName())){
                    errMsg.append("收款账户为空;");
                    vo.setFundStatusCd("1");//异常
                }
                if(vo.getAmountDou()==null){
                    errMsg.append("来款金额为空;");
                    vo.setFundStatusCd("1");//异常
                }
                if(vo.getAcceptDate()==null){
                    errMsg.append("交易时间为空;");
                    vo.setFundStatusCd("1");//异常
                }
                if(StringUtils.isBlank(vo.getComeName())){
                    errMsg.append("来款账户为空;");
                    vo.setFundStatusCd("1");//异常
                }
                if(StringUtils.isBlank(vo.getComeCode())){
                    errMsg.append("来款账号为空;");
                    vo.setFundStatusCd("1");//异常
                }
                if(StringUtils.isBlank(vo.getFundTypCd())){
                    errMsg.append("资金类型为空;");
                    vo.setFundStatusCd("1");//异常
                }
                if("1".equals(vo.getFundStatusCd())){
                    vo.setFundStatusCdNm(errMsg.toString());
                }
            }
        }else{
            BaseLogUtils.info(logger,"importXls","导入资金="+filePath+",记录条数=0");
        }
        return list;
    }

    /**
     * 读取txt文件中保险来款数据
     * @param filePath
     * @return
     * @throws BaseException
     */
    public static List<InsCapFundVO> importInsIncomeTxt(String filePath) throws BaseException {
        if (StringUtils.isBlank(filePath)) {
            throw new BaseException("文件路径不能为空！");
        }
        File file = new File(PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_ROOT_PATH) + filePath);
        if (!file.exists() || !file.isFile()) {
            throw new BaseException("未找到文件" + filePath);
        }
        String tempString = null;
        String[] tempArr = null;
        int line = 0;
        List<InsCapFundVO> list = new ArrayList<>();
        InsCapFundVO vo = null;
        try {
            RandomAccessFile ac = new RandomAccessFile(file, "r");
            while ((tempString = ac.readLine()) != null) {
                tempString = new String(tempString.getBytes("ISO-8859-1"), "UTF-8");
                logger.debug("Line：" + line + "：" + tempString);
                // 跳过标题行
                if (line == 0) {
                    line = 1;
                    continue;
                }
                if (StringUtils.isBlank(tempString)) {
                    throw new BaseException("第" + line + "行数据不能为空！");
                }
                // 付款日期(yyyy-mm-dd);收款账号;收款账户;来款金额(元);来款账号;来款户名;支付表号;备注(不可出现英文分号)
                tempArr = tempString.split(";");
                // 校验必填项：付款日期、来款金额、支付表号
                if (StringUtils.isBlank(tempArr[0])) {
                    throw new BaseException("第" + line + "行数据付款日期不能为空！");
                }
                if (tempArr.length < 4 || StringUtils.isBlank(tempArr[3])) {
                    throw new BaseException("第" + line + "行数据来款金额不能为空！");
                }
                if (tempArr.length < 7 || StringUtils.isBlank(tempArr[6])) {
                    throw new BaseException("第" + line + "行数据支付表号不能为空！");
                }
                vo = new InsCapFundVO();
                vo.setAcceptDate(DateUtil.getDateByStringTime(tempArr[0]));
                vo.setAmount(Double.valueOf(tempArr[3]));
                vo.setPayNo(tempArr[6]);
                if (StringUtils.isNotBlank(tempArr[1])) {
                    vo.setAcceptCode(tempArr[1]);
                }
                if (StringUtils.isNotBlank(tempArr[2])) {
                    vo.setAcceptName(tempArr[1]);
                }
                if (StringUtils.isNotBlank(tempArr[4])) {
                    vo.setComeCode(tempArr[4]);
                }
                if (StringUtils.isNotBlank(tempArr[5])) {
                    vo.setComeName(tempArr[5]);
                }
                if (tempArr.length == 8 && StringUtils.isNotBlank(tempArr[7])) {
                    vo.setDocketRem(tempArr[7]);
                }
                list.add(vo);
                line++;
            }
            ac.close();
            return list;
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            logger.error("文件处理错误！", e);
            throw new BaseException("文件处理错误！because：" + e.getMessage());
        }
    }





}
